package com.onesatoshi.mm;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.onesatoshi.mm.db.Chat;
import com.onesatoshi.mm.db.ChatDao;
import com.onesatoshi.mm.db.Setting;
import com.onesatoshi.mm.db.SettingDao;
import com.onesatoshi.mm.db.User;
import com.onesatoshi.mm.db.UserDao;
import com.onesatoshi.mm.util.AccessibilityUtil;
import com.onesatoshi.mm.util.DeviceUtil;
import com.onesatoshi.mm.util.ImageUtils;
import com.onesatoshi.mm.util.NetStateUtils;
import com.onesatoshi.mm.util.SimplePreference;
import com.onesatoshi.mm.util.StringUtils;
import com.onesatoshi.mm.util.TimeUtil;
import com.socks.okhttp.plus.OkHttpProxy;
import com.socks.okhttp.plus.callback.OkCallback;
import com.socks.okhttp.plus.parser.OkTextParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_SCROLLED;
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOWS_CHANGED;
import static com.onesatoshi.mm.Config.ADD_CUSTOMER_RUNNABLE_PERIOD;
import static com.onesatoshi.mm.Config.ADD_USER_START_HOUR;
import static com.onesatoshi.mm.Config.MASK_AUTO_ADD_CUSTOMER;
import static com.onesatoshi.mm.Config.MASK_AUTO_POST_SNS;
import static com.onesatoshi.mm.Config.POST_SNS_RUNNABLE_PERIOD;
import static com.onesatoshi.mm.Config.RUNNABLE_DELAY;
import static com.onesatoshi.mm.Config.taskMask;

/**
 * 辅助服务
 */
public class WxRobotService extends AccessibilityService {

    public static final String TAG = WxRobotService.class.getName();

    private int luckyMoneyStep = -1;
    private int addPhoneBookStep = -1;
    private int addNearbyStep = -1;
    private int autoReplyStep = -1;
    private int addCustomerStep = -1;
    private int postSnsStep = -1;
    private int snsAutoPrizeStep = -1;
    private int acceptAdd2GroupStep = -1;

    private User user = null;

    // 添加通讯录好友
    private String toAddWxId = null;

    private HashSet<String> clickedSet = new HashSet<>();

    // 添加附近的人
    private HashSet<String> nearbySet = new HashSet<>();

    // 自动接受好友申请并加群聊
    private HashSet<String> groupSet = new HashSet<>();

    private PowerManager.WakeLock mWakelock;

    private long waitSec = 0;

    private Vibrator vibrator;//震动
    private MediaPlayer mediaplayer;//提示音

    private int doubleWXTag_POST_SNS = Config.DOUBLE_WEIXIN_CHOOSE;
    private int doubleWXTag_ADD_USER = Config.DOUBLE_WEIXIN_CHOOSE;

    private String userStatus = "";

    private Setting setting = null;

    private boolean frenquetlyWarning = false;

    //    private Lock lock = new ReentrantLock();
    // stock times
    private long lastEventTimeStamp = System.currentTimeMillis();

    @Override
    public void onAccessibilityEvent(final AccessibilityEvent event) {

        int eventType = event.getEventType();

        if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
//            Log.d(TAG, event.getPackageName() + "\t" + event.getClassName());
            return;
        }

        Log.d(TAG, event.toString());

        // 修改悬浮框 信息
        if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {

            TasksWindow.changeMsg(event.getPackageName() + "\n" + event.getClassName());
            Log.d(TAG, event.getPackageName() + "\t" + event.getClassName());
        }

        if (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
            //通知栏事件
            if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {

                Notification notification = (Notification) event.getParcelableData();

                // 事件附加信息
                String tickerText = String.valueOf(notification.tickerText);
                Log.i(TAG, "接收到通知，【" + tickerText + "】");

                String[] cc = tickerText.split(":");
                if (cc.length >= 2) {
                    String nickName = cc[0].trim();// 发送人
                    String content = cc[1].trim(); // 发送信息

                    ChatDao chatDao = new ChatDao(getApplicationContext());
                    Chat chat = new Chat();
                    chat.setNickname(nickName);
                    chat.setWxid("");
                    chat.setDeviceid(SimplePreference.getString(SpConstant.SP_DEVICES_ID, "", getApplicationContext()));
                    chat.setType("0");
                    chat.setContent(content);
                    chat.setStatus("0");
                    chatDao.save(chat);

                    Log.i(TAG, "保存本地聊天记录，【" + tickerText + "】");
                }
            }
        }


        // 微信双开
        if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            // 应用双开，点击某一个
            if (event.getClassName() != null && "com.android.internal.app.ResolverActivity".equals(event.getClassName())) {
                AccessibilityNodeInfo appListRoot = getRootInActiveWindow();
                if (appListRoot != null) {

                    String appViewId = "";

                    if (Config.taskMask == MASK_AUTO_POST_SNS) {
                        if (0 == doubleWXTag_POST_SNS) {
                            appViewId = "android.miui:id/app1";
                        } else {
                            appViewId = "android.miui:id/app2";
                        }

                        List<AccessibilityNodeInfo> appNode = appListRoot.findAccessibilityNodeInfosByViewId(appViewId);
                        if (appNode != null && appNode.size() > 0) {
                            appNode.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);

                            Log.i(TAG, "doubleWXTag_POST_SNS:" + doubleWXTag_POST_SNS);
                            // 切换
                            doubleWXTag_POST_SNS = 1 - doubleWXTag_POST_SNS;
                        } else {
                            Log.e(TAG, "appNde is null");
                        }
                    } else if (Config.taskMask == MASK_AUTO_ADD_CUSTOMER) {

                        if (0 == doubleWXTag_ADD_USER) {
                            appViewId = "android.miui:id/app1";
                        } else {
                            appViewId = "android.miui:id/app2";
                        }

                        List<AccessibilityNodeInfo> appNode = appListRoot.findAccessibilityNodeInfosByViewId(appViewId);
                        if (appNode != null && appNode.size() > 0) {
                            appNode.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);

                            Log.i(TAG, "doubleWXTag_ADD_USER:" + doubleWXTag_ADD_USER);

                            // 切换
                            doubleWXTag_ADD_USER = 1 - doubleWXTag_ADD_USER;
                        } else {
                            Log.e(TAG, "appNde is null");
                        }
                    } else {
                        Log.e(TAG, "wx switch error, unknown Config.taskMask:" + Config.taskMask);
                    }
                }
            }
        }

        if ((event.getPackageName() != null
                && ("com.tencent.mm".equals(event.getPackageName())
                || "com.sohu.inputmethod.sogou.xiaomi".equals(event.getPackageName())
                || "android".equals(event.getPackageName()))
                || "com.android.systemui".equals(event.getPackageName()))

                || (event.getPackageName() == null && eventType == TYPE_WINDOWS_CHANGED)) {

            lastEventTimeStamp = System.currentTimeMillis();
            switch (Config.taskMask) {
                // 自动回复消息
                case Config.MASK_AUTO_REPLY:
                    processAutoRepay(event);
                    break;

                // 自动添加附近的人
                case Config.MASK_AUTO_ADD_NEARBY:
                    processNearbyEvent(event);
                    break;

                // 自动添加通讯录好友
                case Config.MASK_AUTO_ADD_PHONEBOOK:
                    addPhoneBook(event);
                    break;

                // 自动添加客户
                case Config.MASK_AUTO_ADD_CUSTOMER:
                    Log.d(TAG, "addCustomerStep:" + addCustomerStep);

                    if (user != null) {

                        Log.d(TAG, "user：" + user.getPhone() + ", addCustomerStep:" + addCustomerStep);

                        addCustomerBySearch(event);

                    } else if (addCustomerStep == -1) {

                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
                        Config.taskMask = Config.MASK_DEFAULT;

                        Log.d(TAG, "user is null, 按下Home键，taskMask：" + Config.taskMask + ", addCustomerStep:" + addCustomerStep);
                    } else {
                        Log.d(TAG, "user is null, addCustomerStep：" + addCustomerStep);
                    }

                    break;

                // 自动发朋友圈
                case Config.MASK_AUTO_POST_SNS:

                    processPostSns(event);

                    break;

                // 自动抢红包
                case Config.MASK_AUTO_OPEN_LUCKY_MONEY:
                    processLuckMoneyEvent(event);
                    break;

                // 朋友圈自动点赞
                case Config.MASK_AUTO_SNS_PRIZE:
                    processAutoPrize(event);
                    break;

                // 接受好友请求并添加到群聊
                case Config.MASK_AUTO_ACCEPT_FRIEND_ADD_2GROUP:
                    processAcceptFriendAdd2Group(event);
                    break;

                // 自动爬取群组信息
                case Config.MASK_AUTO_CRAWL_GROUPMSG:
                    processCrawlGroupMsg(event);
                    break;
                default:

                    Log.e(TAG, "mask is default:" + taskMask);
                    break;
            }
        }

    }

    @Override
    protected void onServiceConnected() {

        super.onServiceConnected();

        Log.i(TAG, "服务已开启");

        Toast.makeText(this, "服务已开启", Toast.LENGTH_SHORT).show();

        final String deviceId = SimplePreference.getString(SpConstant.SP_DEVICES_ID, DeviceUtil.getDeviceId(getApplicationContext()), getApplicationContext());

        // 更新data信息
        final Handler getDataHandler = new Handler();
        Runnable getDataRunnable = new Runnable() {
            @Override
            public void run() {

                // 检查网络连接
                if (!NetStateUtils.isNetworkConnected(getApplicationContext())) {
                    Log.e(TAG, "网络连接异常, " + NetStateUtils.getConnectedType(getApplicationContext()));
                } else {

                    // 获取配置
                    getPropertyFromWebSync();

                    if (!frenquetlyWarning) {
                        // 配置抓取周期
                        SettingDao settingDao = new SettingDao(getApplicationContext());
                        Setting setting = settingDao.findByProperty("add_user_period_type");
                        if (setting != null) {

                            String periodType = setting.getValue();
                            if ("0".equals(periodType)) {
                                // 使用本地配置
                                Log.i(TAG, "使用本地配置，periodType：" + periodType + ", Config.ADD_CUSTOMER_RUNNABLE_PERIOD:" + ADD_CUSTOMER_RUNNABLE_PERIOD);
                            } else {
                                // 使用服务器配置
                                settingDao = new SettingDao(getApplicationContext());
                                Setting serverSetting = settingDao.findByProperty("add_user_period");
                                if (serverSetting != null) {
                                    ADD_CUSTOMER_RUNNABLE_PERIOD = Long.valueOf(serverSetting.getValue());
                                    Log.i(TAG, "使用服务器配置，periodType：" + periodType + ", Config.ADD_CUSTOMER_RUNNABLE_PERIOD:" + ADD_CUSTOMER_RUNNABLE_PERIOD);

                                }
                            }
                        } else {
                            Log.e(TAG, "setting add_user_period_type is null");
                        }
                    } else {
                        // wait an hour
                        ADD_CUSTOMER_RUNNABLE_PERIOD = Config.FREQUENT_WAIT_MILLSEC;
                    }

                    // 发朋友圈
                    SettingDao settingDao = new SettingDao(getApplicationContext());
                    Setting setting = settingDao.findByProperty("post_sns_period_type");
                    if (setting != null) {

                        String periodType = setting.getValue();
                        if ("0".equals(periodType)) {
                            // 使用本地配置
                            Log.i(TAG, "使用本地配置，periodType：" + periodType + ", Config.POST_SNS_RUNNABLE_PERIOD:" + POST_SNS_RUNNABLE_PERIOD);
                        } else {
                            // 使用服务器配置
                            settingDao = new SettingDao(getApplicationContext());
                            Setting serverSetting = settingDao.findByProperty("post_sns_period");
                            if (serverSetting != null) {
                                POST_SNS_RUNNABLE_PERIOD = Long.valueOf(serverSetting.getValue());
                                Log.i(TAG, "使用服务器配置，periodType：" + periodType + ", Config.POST_SNS_RUNNABLE_PERIOD:" + POST_SNS_RUNNABLE_PERIOD);
                            }
                        }
                    } else {
                        Log.e(TAG, "setting post_sns_period_type is null");
                    }

                    // 任务执行时间段设置
                    settingDao = new SettingDao(getApplicationContext());
                    setting = settingDao.findByProperty("task_work_time_type");
                    if (setting != null) {

                        String workTimeType = setting.getValue();
                        if ("0".equals(workTimeType)) {
                            // 使用本地配置
                            Log.i(TAG, "使用本地配置，workTimeType：" + workTimeType + ", Config.ADD_USER_START_HOUR:" + ADD_USER_START_HOUR);
                        } else {
                            // 使用服务器配置
                            settingDao = new SettingDao(getApplicationContext());
                            Setting serverSetting = settingDao.findByProperty("task_work_time");
                            if (serverSetting != null) {
                                String workTime[] = serverSetting.getValue().split(",");
                                if (workTime != null && workTime.length >= 4) {
                                    Config.ADD_USER_START_HOUR = Integer.valueOf(workTime[0]);
                                    Config.ADD_USER_STOP_HOUR = Integer.valueOf(workTime[1]);
                                    Config.POST_SNS_START_HOUR = Integer.valueOf(workTime[2]);
                                    Config.POST_SNS_STOP_HOUR = Integer.valueOf(workTime[3]);
                                    Log.i(TAG, "使用服务器配置，workTimeType：" + workTimeType + ", serverSetting.getValue():" + serverSetting.getValue());
                                }
                            }
                        }
                    } else {
                        Log.e(TAG, "setting post_sns_period_type is null");
                    }

                    // sns
                    settingDao = new SettingDao(getApplicationContext());
                    setting = settingDao.findByProperty(Config.SNS_URL_KEY);
                    if (setting == null || !Config.SNS_AVAILABLE_STATUS.equals(setting.getStatus())) {
                        getSnsFromWebSync();
                    }

                    // user
                    UserDao userDao = new UserDao(getApplicationContext());
                    int userNum = userDao.countUndoNum();
                    // 低于两条，则开始获取数据
                    if (userNum == 0) {
                        Log.i(TAG, "获取新用户");
                        getUserFromWebSync();
                    }
                }

                // long time no response, then go back
                if (System.currentTimeMillis() - lastEventTimeStamp >= Config.EVENT_BETWEEN_MILLSEC_MAX) {

                    Log.i(TAG, "long time no response, go back");
                    if (Config.taskMask == Config.MASK_AUTO_POST_SNS) {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        if (postSnsStep != -1) {
                            postSnsStep -= 1;
                        }

                    } else if (Config.taskMask == Config.MASK_AUTO_ADD_CUSTOMER) {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        if (addCustomerStep != -1) {
                            addCustomerStep -= 1;
                        }
                    }

                    // 唤醒微信
                    Log.i(TAG, "点亮微信");
                    wakeUpScreenAndWeiXin(getApplicationContext());

                }


                getDataHandler.postDelayed(this, Config.QUERY_RUNNABLE_PERIOD);
                Log.i(TAG, "定时刷新配置信息");
            }
        };
        getDataHandler.postDelayed(getDataRunnable, 1000);


        // 提示信息
        final Handler taskInfoHandler = new Handler();
        Runnable taskInfoRunnable = new Runnable() {
            @Override
            public void run() {

                TasksWindow.changeMsg("deviceId:" + deviceId + ", waitSec:" + waitSec / 1000);
                Log.d(TAG, "deviceId:" + deviceId + ", waitSec:" + waitSec / 1000);
                waitSec -= RUNNABLE_DELAY;
                taskInfoHandler.postDelayed(this, RUNNABLE_DELAY);
            }
        };
        taskInfoHandler.postDelayed(taskInfoRunnable, RUNNABLE_DELAY);

        // 更新用户信息，并且唤醒微信执行加人动作
        final Handler getAndAddUserHandler = new Handler();
        Runnable getAndAddUserRunnable = new Runnable() {
            @Override
            public void run() {

                Log.i(TAG, "now Hour:" + TimeUtil.getHour());

                int userNum = 0;
                // 检查网络连接
                if (!NetStateUtils.isNetworkConnected(getApplicationContext())) {
                    Log.e(TAG, "网络连接异常, " + NetStateUtils.getConnectedType(getApplicationContext()));
                } else if (TimeUtil.getHour() >= Config.ADD_USER_START_HOUR && TimeUtil.getHour() <= Config.ADD_USER_STOP_HOUR) {

                    if (Config.taskMask == Config.MASK_DEFAULT) {

                        UserDao userDao = new UserDao(getApplicationContext());
                        userNum = userDao.countUndoNum();
                        Log.i(TAG, "本地待处理用户数userNum:" + userNum);

                        // 低于两条，则开始获取数据
                        if (userNum != 0) {
                            // 播放提示
                            playTipSound();

                            // 唤醒微信
                            Log.i(TAG, "定时获取新用户，点亮微信，更新taskMask：" + Config.taskMask);
                            wakeUpScreenAndWeiXin(getApplicationContext());

                            // 判断有没有数据
                            userDao = new UserDao(getApplicationContext());
                            user = userDao.findTop2Add();

                            Config.taskMask = Config.MASK_AUTO_ADD_CUSTOMER;
                            lastEventTimeStamp = System.currentTimeMillis();

                        } else {
                            Log.e(TAG, "no user available");
                        }

                    } else {
                        Log.i(TAG, "微信 is busy, Config.taskMask:" + Config.taskMask);
                    }
                }

                waitSec = ADD_CUSTOMER_RUNNABLE_PERIOD;

                TasksWindow.changeMsg("deviceId:" + deviceId + ", userNum:" + userNum + ", 等待时间:" + waitSec);

                // cancel
                if (ADD_CUSTOMER_RUNNABLE_PERIOD == Config.FREQUENT_WAIT_MILLSEC) {
                    frenquetlyWarning = true;
                }

                getAndAddUserHandler.postDelayed(this, ADD_CUSTOMER_RUNNABLE_PERIOD);
            }
        };
        getAndAddUserHandler.postDelayed(getAndAddUserRunnable, RUNNABLE_DELAY);
        waitSec = RUNNABLE_DELAY;

        // 自动发朋友圈
        final Handler autoPostSnsHandler = new Handler();
        Runnable autoPostSnsRunnable = new Runnable() {
            @Override
            public void run() {

                Log.i(TAG, "now Hour:" + TimeUtil.getHour());

                if (TimeUtil.getHour() >= Config.POST_SNS_START_HOUR && TimeUtil.getHour() <= Config.POST_SNS_STOP_HOUR) {

                    SettingDao settingDao = new SettingDao(getApplicationContext());
                    setting = settingDao.findByProperty(Config.SNS_URL_KEY);

                    if (setting != null && Config.SNS_AVAILABLE_STATUS.equals(setting.getStatus())) {
                        final String snsurl = setting.getValue();

                        Runnable r = new Runnable() {
                            @Override
                            public void run() {
                                try {

                                    Bitmap snsImgBitmap = ImageUtils.getPic(snsurl);

                                    Thread.sleep(20000);
                                    if (snsImgBitmap != null) {

                                        ImageUtils.saveImageToGallery(getApplicationContext(), snsImgBitmap);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        new Thread(r).start();

                        try {
                            Thread.sleep(30000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (Config.taskMask == Config.MASK_DEFAULT) {

                            // 唤醒微信
                            Config.taskMask = Config.MASK_AUTO_POST_SNS;
                            lastEventTimeStamp = System.currentTimeMillis();

                            Log.i(TAG, "点亮微信，自动发朋友圈，更新taskMask：" + Config.taskMask);
                            wakeUpScreenAndWeiXin(getApplicationContext());

                            autoPostSnsHandler.postDelayed(this, POST_SNS_RUNNABLE_PERIOD);
                        } else {
                            Log.i(TAG, "微信 is busy, Config.taskMask:" + Config.taskMask);
                        }

                    } else {
                        Log.e(TAG, "sns not available");
                    }
                }
            }
        };
        autoPostSnsHandler.postDelayed(autoPostSnsRunnable, RUNNABLE_DELAY + 30000);
    }

    /**
     * 播放提示音
     */
    private void playTipSound() {

        //震动
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(1000l);

        // 铃声（这里是先释放掉内存）
        if (mediaplayer != null) {
            mediaplayer.stop();
            mediaplayer.release();
            mediaplayer = null;
        }
        mediaplayer = new MediaPlayer();
        try {
            mediaplayer.setDataSource(WxRobotService.this, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mediaplayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaplayer.start();

        vibrator.cancel();
        if (mediaplayer.isPlaying()) {
            mediaplayer.stop();
        }
    }

    // 获取配置信息
    private void getPropertyFromWebSync() {

        String URL_GET_PROPERTY = Config.SERVER_URL + "/wx/setting/get";

        OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(URL_GET_PROPERTY)
                .get().build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            String msg = response.body().string();

            Log.i(TAG, "更新配置信息，htmlStr:" + msg);

            if (!StringUtils.isBlank(msg)) {

                JSONObject jsonObject = new JSONObject(msg);

                Iterator<String> iter = jsonObject.keys();

                while (iter.hasNext()) {

                    String prop = iter.next();
                    String value = jsonObject.getString(prop);

                    SettingDao settingDao = new SettingDao(getApplicationContext());
                    Setting setting = settingDao.findByProperty(prop);
                    if (setting == null) {
                        setting = new Setting();
                        setting.setProperty(prop);
                        setting.setValue(value);
                        setting.setStatus(Config.CONFIG_AVAILABLE_STATUS);

                        settingDao = new SettingDao(getApplicationContext());
                        settingDao.save(setting);

                        Log.i(TAG, "保存配置信息，" + prop + "信息");

                    } else {
                        setting.setValue(value);

                        settingDao = new SettingDao(getApplicationContext());
                        settingDao.update(setting);
                        Log.i(TAG, "更新配置信息，" + prop + "信息");
                    }
                }
            } else {
                Log.e(TAG, "更新配置信息失败");
            }

        } catch (IOException e) {

            Log.e(TAG, "更新配置信息，请求失败");
            TasksWindow.changeMsg("更新配置信息，请求失败," + e.getMessage());

            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 获取配置信息
    private void getPropertyFromWebAsync() {

        String URL_GET_PROPERTY = Config.SERVER_URL + "/wx/setting/get";

        OkHttpProxy.get()
                .url(URL_GET_PROPERTY)
                .tag(this)
                .enqueue(new OkCallback<String>(new OkTextParser()) {
                    @Override
                    public void onSuccess(int code, String msg) {

                        Log.i(TAG, "更新配置信息，htmlStr:" + msg);
                        try {

                            if (msg.startsWith("\ufeff")) {
                                msg = msg.substring(1);
                            }

                            JSONObject jsonObject = new JSONObject(msg);

                            Iterator<String> iter = jsonObject.keys();

                            while (iter.hasNext()) {

                                String prop = iter.next();
                                String value = jsonObject.getString(prop);

                                SettingDao settingDao = new SettingDao(getApplicationContext());
                                Setting setting = settingDao.findByProperty(prop);
                                if (setting == null) {
                                    setting = new Setting();
                                    setting.setProperty(prop);
                                    setting.setValue(value);
                                    setting.setStatus(Config.CONFIG_AVAILABLE_STATUS);

                                    settingDao = new SettingDao(getApplicationContext());
                                    settingDao.save(setting);

                                    Log.i(TAG, "保存配置信息，" + prop + "信息");

                                } else {
                                    setting.setValue(value);

                                    settingDao = new SettingDao(getApplicationContext());
                                    settingDao.update(setting);
                                    Log.i(TAG, "更新配置信息，" + prop + "信息");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Throwable e) {

                        Log.e(TAG, "更新配置信息，请求失败");
                        e.printStackTrace();
                        TasksWindow.changeMsg("更新配置信息，请求失败," + e.getMessage());
                    }
                });
    }

    // 从服务器获取新的用户信息
    private void getUserFromWebAsync() {

        String URL_GET_USER = Config.SERVER_URL + "/wx/getone?deviceId=" + DeviceUtil.getDeviceId(getApplicationContext());

        OkHttpProxy.get()
                .url(URL_GET_USER)
                .tag(this)
                .enqueue(new OkCallback<String>(new OkTextParser()) {

                    @Override
                    public void onSuccess(int code, String msg) {

                        Log.i(TAG, "查询客户手机号，msg:" + msg);

                        // 数据为空
                        if ("0".equals(msg)) {
                            Log.e(TAG, "查询客户手机号，没有有效手机号了");
                            return;
                        }

                        try {
                            JSONObject jsonObject = new JSONObject(msg);
                            String name = jsonObject.getString("name");
                            String phone = jsonObject.getString("phone");

                            UserDao userDao = new UserDao(getApplicationContext());
                            // 添加用户
                            if (userDao.findByPhone(phone) == null) {
                                User user = new User();
                                user.setUsername(name);
                                user.setPhone(phone);
                                user.setStatus("0");
                                user.setNickname("");
                                user.setWxid("");

                                userDao = new UserDao(getApplicationContext());
                                userDao.save(user);

                                Log.i(TAG, "查询客户手机号，添加用户信息:" + user.getPhone());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {

                        Log.e(TAG, "查询客户手机号，请求失败");
                        e.printStackTrace();
                        TasksWindow.changeMsg("查询客户手机号，请求失败:" + e.getMessage());
                    }

                });
    }

    // 从服务器获取新的用户信息
    private void getUserFromWebSync() {

        String URL_GET_USER = Config.SERVER_URL + "/wx/getone?deviceId=" + DeviceUtil.getDeviceId(getApplicationContext());

        OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(URL_GET_USER)
                .get().build();
        Call call = client.newCall(request);

        try {

            Response response = call.execute();
            String msg = response.body().string();

            Log.i(TAG, "查询客户手机号，msg:" + msg);

            // 数据为空
            if ("0".equals(msg)) {
                Log.e(TAG, "查询客户手机号，没有有效手机号了");
                return;
            }
            JSONObject jsonObject = new JSONObject(msg);
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            UserDao userDao = new UserDao(getApplicationContext());
            // 添加用户
            if (userDao.findByPhone(phone) == null) {
                User user = new User();
                user.setUsername(name);
                user.setPhone(phone);
                user.setStatus(Config.USER_AVAILABLE_STATUS);
                user.setNickname("");
                user.setWxid("");

                userDao = new UserDao(getApplicationContext());
                userDao.save(user);

                Log.i(TAG, "查询客户手机号，添加用户信息:" + user.getPhone());
            }


        } catch (IOException e) {
            Log.e(TAG, "查询客户手机号，请求失败");
            e.printStackTrace();
            TasksWindow.changeMsg("查询客户手机号，请求失败:" + e.getMessage());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 获取SNS
    private void getSnsFromWebSync() {

        String URL_GET_PROPERTY = Config.SERVER_URL + "/wx/sns/get?deviceId=" + DeviceUtil.getDeviceId(getApplicationContext());

        Log.i(TAG, "查询sns");

        OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(URL_GET_PROPERTY)
                .get().build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            String msg = response.body().string();

            Log.i(TAG, "查询sns，msg:" + msg);

            // 数据为空
            if ("0".equals(msg)) {
                Log.e(TAG, "查询sns，没有有效sns了");
                return;
            }

            JSONObject jsonObject = new JSONObject(msg);
            String url = jsonObject.getString("url");
            String content = jsonObject.getString("content");

            SettingDao settingDao = new SettingDao(getApplicationContext());
            Setting setting = settingDao.findByProperty(Config.SNS_URL_KEY);
            // 添加用户
            if (setting == null) {
                setting = new Setting();
                setting.setProperty(Config.SNS_URL_KEY);
                setting.setValue(url);
                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                settingDao = new SettingDao(getApplicationContext());
                settingDao.save(setting);

            } else {
                setting.setValue(url);
                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                settingDao = new SettingDao(getApplicationContext());
                settingDao.save(setting);
            }

            settingDao = new SettingDao(getApplicationContext());
            setting = settingDao.findByProperty(Config.SNS_CONTENT_KEY);

            if (setting == null) {
                setting = new Setting();
                setting.setProperty(Config.SNS_CONTENT_KEY);
                setting.setValue(content);
                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                settingDao = new SettingDao(getApplicationContext());
                settingDao.save(setting);

            } else {
                setting.setValue(content);
                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                settingDao = new SettingDao(getApplicationContext());
                settingDao.save(setting);
            }

            Log.i(TAG, "update sns:" + content);


        } catch (IOException e) {

            Log.e(TAG, "更新sns，请求失败");
            e.printStackTrace();
            TasksWindow.changeMsg("更新sns，请求失败," + e.getMessage());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 获取SNS
    private void getSnsFromWebAsync() {

        String URL_GET_PROPERTY = Config.SERVER_URL + "/wx/sns/get?deviceId=" + DeviceUtil.getDeviceId(getApplicationContext());

        Log.i(TAG, "查询sns");

        OkHttpProxy.get()
                .url(URL_GET_PROPERTY)
                .tag(this)
                .enqueue(new OkCallback<String>(new OkTextParser()) {
                    @Override
                    public void onSuccess(int code, String msg) {

                        Log.i(TAG, "查询sns，msg:" + msg);

                        // 数据为空
                        if ("0".equals(msg)) {
                            Log.e(TAG, "查询sns，没有有效sns了");
                            return;
                        }

                        try {

                            JSONObject jsonObject = new JSONObject(msg);
                            String url = jsonObject.getString("url");
                            String content = jsonObject.getString("content");

                            SettingDao settingDao = new SettingDao(getApplicationContext());
                            Setting setting = settingDao.findByProperty(Config.SNS_URL_KEY);
                            // 添加用户
                            if (setting == null) {
                                setting = new Setting();
                                setting.setProperty(Config.SNS_URL_KEY);
                                setting.setValue(url);
                                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                                settingDao = new SettingDao(getApplicationContext());
                                settingDao.save(setting);

                            } else {
                                setting.setValue(url);
                                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                                settingDao = new SettingDao(getApplicationContext());
                                settingDao.save(setting);
                            }

                            settingDao = new SettingDao(getApplicationContext());
                            setting = settingDao.findByProperty(Config.SNS_CONTENT_KEY);

                            if (setting == null) {
                                setting = new Setting();
                                setting.setProperty(Config.SNS_CONTENT_KEY);
                                setting.setValue(content);
                                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                                settingDao = new SettingDao(getApplicationContext());
                                settingDao.save(setting);

                            } else {
                                setting.setValue(content);
                                setting.setStatus(Config.SNS_AVAILABLE_STATUS);

                                settingDao = new SettingDao(getApplicationContext());
                                settingDao.save(setting);
                            }

                            Log.i(TAG, "update sns:" + content);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Throwable e) {

                        Log.e(TAG, "更新sns，请求失败");
                        e.printStackTrace();
                        TasksWindow.changeMsg("更新sns，请求失败," + e.getMessage());
                    }
                });
    }


    /**
     * 自动回复-----------------------------------------------------start---------------------------------------
     */
    public void processAutoRepay(final AccessibilityEvent event) {

        /**
         * 通知类，监听消息通知，通知栏、Toast会触发该类型事件
         */
        if (autoReplyStep == -1 && event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {

            // 有人发信息 记录信息内容 会直接点开信息
            if (handleNotification(event, "我通过了你的朋友验证请求，现在我们可以开始聊天了")) {
                autoReplyStep = 1;
            }

        } else if (autoReplyStep == 1) {

            AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/alm", 0, "自动回复输入框");

            if (nodeInfo == null) {
                Log.e(TAG, "nodeinfo is null");
                return;
            }

            String introduce = "自我介绍一下";

            SettingDao settingDao = new SettingDao(getApplicationContext());
            Setting setting = settingDao.findByProperty("introduce");
            if (setting != null) {
                introduce = setting.getValue();
            }

            if (inputTextByNodeInfo(nodeInfo, introduce, true)) {

                if (findAndClickNodeByViewId("com.tencent.mm:id/als", 0, "发送")) {

                    autoReplyStep = 2;
                }

            }

        }

    }


    /**
     * 有人发信息 记录信息内容 会直接点开信息
     *
     * @param event
     */
    private boolean handleNotification(AccessibilityEvent event, String keyWord) {

        //通知栏事件
        if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {

            Notification notification = (Notification) event.getParcelableData();

            // 事件附加信息
            String tickerText = String.valueOf(notification.tickerText);
            Log.i(TAG, "接收到通知，【" + tickerText + "】");


            if (tickerText != null && !"".equals(tickerText)) {
                String[] cc = tickerText.split(":");

                if (cc.length >= 2) {
                    String noticeWxNickName = cc[0].trim();// 发送人
                    String content = cc[1].trim(); // 发送信息

                    // jia命令，特殊消息处理
                    if (content.startsWith(keyWord)) {
                        // 拉起微信界面
                        notifyWechat(event);

                        return true;
                    }

                }
            }
        }

        return false;
    }


    /**
     * 拉起微信界面
     *
     * @param event event
     */
    private void notifyWechat(AccessibilityEvent event) {

        if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {

            Notification notification = (Notification) event.getParcelableData();

            PendingIntent pendingIntent = notification.contentIntent;
            try {
                pendingIntent.send();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 自动添加通讯录好友-----------------------------------------------------start---------------------------------------
     *
     */

    /***
     *  自动添加通讯录好友
     */
    private void addPhoneBook(final AccessibilityEvent event) {

        if (addPhoneBookStep == -1) {
            if (event.getText() != null && event.getText().size() > 0) {
                for (int i = 0; i < event.getText().size(); i++) {

                    String text = event.getText().get(i).toString();
                    if (("微信".equals(text) || "通讯录".equals(text) || "发现".equals(text))) {
                        addPhoneBookStep = 0;
                        break;
                    }
                }
            }
        } else if (addPhoneBookStep == 0) {

            // 1.在主页面，点击+
            if (findAndClickNodeByViewId("com.tencent.mm:id/ij", 1, "+")) {
                addPhoneBookStep = 1;
            }

        } else if (addPhoneBookStep == 1) {

            // 2.添加朋友按钮
            if (findAndClickNodeByViewId("com.tencent.mm:id/ki", 1, "添加朋友")) {
                addPhoneBookStep = 2;
            }

        } else if (addPhoneBookStep == 2) {

            // 3.手机联系人
            if (findAndClickNodeByText("添加或邀请通讯录中的朋友")) {
                addPhoneBookStep = 3;
            }

        } else if (addPhoneBookStep == 3) {

            if (processAddFriend()) {

                addPhoneBookStep = 4;
            } else {

                goBack();
                goBack();
                goBack();
                addPhoneBookStep = -1;
            }

        } else if (addPhoneBookStep == 4) {

            if ("com.tencent.mm.plugin.profile.ui.SayHiWithSnsPermissionUI".equals(event.getClassName().toString())) {


                AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/dx6", 0, "打招呼内容编辑框");
                if (nodeInfo != null) {

                    String sayHello = "我是李延凯";

                    SettingDao settingDao = new SettingDao(getApplicationContext());
                    Setting setting = settingDao.findByProperty("sayhello");
                    if (setting != null) {
                        sayHello = setting.getValue();
                    }

                    inputTextByNodeInfo(nodeInfo, sayHello, false);


                    // 5.点击好友申请发送
                    if (findAndClickNodeByViewId("com.tencent.mm:id/jq", 0, "发送")) {
                        addPhoneBookStep = 5;
                    }

                }
            } else if ("com.tencent.mm.plugin.account.bind.ui.MobileFriendUI".equals(event.getClassName().toString())) {

                if (checkHasAddedByWxId(toAddWxId)) {
                    Log.i(TAG, "未开通验证，直接添加");
                    addPhoneBookStep = 3;
                }
            }
        } else if (addPhoneBookStep == 5) {
            goBack();
            addPhoneBookStep = 3;
        }

    }

    /**
     * 循环点击添加按钮
     */
    private boolean processAddFriend() {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/btz");
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, "<添加> is null");
            return false;
        }


        for (int j = 0; j < bu.size(); j++) {

            AccessibilityNodeInfo info = bu.get(j);

            if (info == null || !info.isClickable()) {
                Log.i(TAG, "不能点击");
                continue;
            }

            if (info.getParent() == null || info.getParent().getChildCount() < 2) {
                Log.i(TAG, "找不到微信号");
                continue;
            }

            String nickName = info.getParent().getChild(1).getChild(0).getText().toString();
            String wxId = info.getParent().getChild(1).getChild(1).getText().toString();


            if (clickedSet.contains(wxId)) {
//                    Log.e(TAG, "已经添加过该微信");
                continue;
            }

            Log.i(TAG, "添加好友，昵称：" + nickName);
            Log.i(TAG, "添加好友，微信号：" + wxId);

            clickedSet.add(wxId);
            toAddWxId = wxId;
            Log.i(TAG, "点击 <添加>");
            info.performAction(AccessibilityNodeInfo.ACTION_CLICK);

            return true;
        }

        return false;
    }

    /**
     * 判断是否不需要验证，即可添加
     */
    private boolean checkHasAddedByWxId(String toFindWxId) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/btz");
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, "<添加> is null");
            return false;
        }

        for (int j = 0; j < bu.size(); j++) {

            AccessibilityNodeInfo info = bu.get(j);
            if (info.getParent() == null || info.getParent().getChildCount() < 3) {
                Log.e(TAG, "找不到微信号");
                continue;
            }

            String nickName = info.getParent().getChild(1).getChild(0).getText().toString();
            String wxId = info.getParent().getChild(1).getChild(1).getText().toString();


            if (toFindWxId.equals(wxId)) {
                if ("已添加".equals(info.getParent().getChild(2).getChild(0).getText().toString())) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 按照手机号自动添加客户-----------------------------------------------------start---------------------------------------
     *
     */

    /***
     *  自动添加客户
     */
    private void addCustomerBySearch(final AccessibilityEvent event) {

        int eventType = event.getEventType();

        String eventClass = "";
        if (event.getClassName() != null) {
            eventClass = event.getClassName().toString();
        }

        if (addCustomerStep == -1) {

            // 微信首页
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.LauncherUI".equals(eventClass)) {

                List<String> searchIdList = new ArrayList<>();
                searchIdList.add("com.tencent.mm:id/ij");
                searchIdList.add("com.tencent.mm:id/iq");

                for (int i = 0; i < searchIdList.size(); i++) {

                    String searchId = searchIdList.get(i);

                    AccessibilityNodeInfo searchNode = findNodeByViewId(searchId, 0, "搜索");
                    if (searchNode != null) {
                        int loop = 10;
                        while (searchNode != null && !searchNode.isClickable() && loop > 0) {
                            loop--;
                            searchNode = searchNode.getParent();
                        }

                        if (searchNode != null) {

                            searchNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            addCustomerStep = 0;

                            Log.d(TAG, "点击 <搜索" + searchId + ">");

                            break;
                        } else {

                            Log.d(TAG, "<搜索" + searchId + "> 不能点击");
                        }
//                        searchNode.recycle();

                    } else {
                        Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
                    }
                }
            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.account.ui.LoginPasswordUI".equals(eventClass)) {

                performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);

                Config.taskMask = Config.MASK_DEFAULT;

                Log.d(TAG, "user is null, 按下Home键，taskMask：" + Config.taskMask + ", addCustomerStep:" + addCustomerStep);

            }
        } else if (addCustomerStep == 0) {

            if ((eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "android.inputmethodservice.SoftInputWindow".equals(eventClass))
                    ||
                    (eventType == AccessibilityEvent.TYPE_VIEW_FOCUSED && "android.widget.EditText".equals(eventClass)) ||
                    (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED && "android.app.Notification".equals(eventClass)) ||
                    (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.fts.ui.FTSMainUI".equals(eventClass))
                    || (eventType == TYPE_WINDOWS_CHANGED)) {

                AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                if (rootNode != null) {

                    List<String> inputSearchIdList = new ArrayList<>();
                    inputSearchIdList.add("com.tencent.mm:id/ka");
                    inputSearchIdList.add("com.tencent.mm:id/kh");

                    for (int i = 0; i < inputSearchIdList.size(); i++) {

                        String inputSearchId = inputSearchIdList.get(i);

                        Log.i(TAG, "inputSearchId:" + inputSearchId);

                        List<AccessibilityNodeInfo> inputSearchNodeList = rootNode.findAccessibilityNodeInfosByViewId(inputSearchId);
                        if (inputSearchNodeList != null) {

                            for (int j = 0; j < inputSearchNodeList.size(); j++) {

                                Log.i(TAG, "inputSearchNodeList.size():" + inputSearchNodeList.size() + ", j:" + j);

                                AccessibilityNodeInfo inputNode = inputSearchNodeList.get(j);

//                                if (inputNode.getText() != null && "搜索".equals(inputNode.getText().toString()) && inputNode.getClassName() != null && "android.widget.EditText".equals(inputNode.getClassName().toString())) {
                                if (inputNode.getClassName() != null && "android.widget.EditText".equals(inputNode.getClassName().toString())) {

                                    if (inputNode.isClickable()) {

                                        inputNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                                        if (inputNode.getText() != null) {
                                            Log.i(TAG, "inputNode.getText():" + inputNode.getText());
                                        }

                                        inputTextByViewId(inputNode, user.getPhone(), true);

                                    } else {
                                        Log.i(TAG, "input not clickable");
                                    }

                                } else {
                                    Log.i(TAG, "input not valid, addCustomerStep:" + addCustomerStep + ", inputNode.getText():" + inputNode.getText() + ", inputNode.getClassName():" + inputNode.getClassName());
                                }
                            }
                        } else {
                            Log.i(TAG, "do not found input, addCustomerStep:" + addCustomerStep);
                        }
                    }


                    rootNode = getRootInActiveWindow();
                    if (rootNode != null) {

                        for (int i = 0; i < inputSearchIdList.size(); i++) {

                            String inputSearchId = inputSearchIdList.get(i);

                            Log.i(TAG, "inputSearchId:" + inputSearchId);

                            List<AccessibilityNodeInfo> inputSearchNodeList = rootNode.findAccessibilityNodeInfosByViewId(inputSearchId);
                            if (inputSearchNodeList != null) {

                                for (int j = 0; j < inputSearchNodeList.size(); j++) {

                                    Log.i(TAG, "inputSearchNodeList.size():" + inputSearchNodeList.size() + ", j:" + j);

                                    AccessibilityNodeInfo inputNode = inputSearchNodeList.get(j);
                                    if (inputNode.getClassName() != null && "android.widget.EditText".equals(inputNode.getClassName().toString())) {
                                        if (inputNode.getText() != null && inputNode.getText().toString().equals(user.getPhone())) {
                                            Log.i(TAG, "inputNode success");
                                            addCustomerStep = 2;
                                        } else {
                                            inputNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                                            if (inputNode.getText() != null) {
                                                Log.i(TAG, "inputNode.getText():" + inputNode.getText());
                                            }

                                            inputTextByViewId(inputNode, user.getPhone(), true);
                                        }
                                    }
                                }
                            }
                        }
                    }

//                    rootNode.recycle();
                }
            } else {

                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }
        } else if (addCustomerStep == 2) {

            // 输入后，可以点击查找了
            if (eventType == TYPE_VIEW_SCROLLED && "android.widget.ListView".equals(eventClass)) {


                List<String> searchPhoneIdList = new ArrayList<>();
                searchPhoneIdList.add("com.tencent.mm:id/bve");
                searchPhoneIdList.add("com.tencent.mm:id/bxb");

                for (int i = 0; i < searchPhoneIdList.size(); i++) {

                    String searchPhoneId = searchPhoneIdList.get(i);

                    AccessibilityNodeInfo findPhoneNode = findNodeByViewId(searchPhoneId, 0, "查找手机/QQ号");
                    if (findPhoneNode != null) {
                        if (findPhoneNode.isClickable()) {
                            findPhoneNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            doSleep(200);
                            addCustomerStep = 3;
                            break;
                        }
                        findPhoneNode.recycle();
                    }
                }

                // 已经是好友了
                if (addCustomerStep == 2) {
                    goBack();
                    goBack();
                    userStatus = Config.USER_ADDED_STATUS;
                    addCustomerStep = 11;

                    Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
                }
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }

        } else if (addCustomerStep == 3) {
            // 正在查找联系人...
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.base.p".equals(eventClass)) {

                addCustomerStep = 4;

            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.ContactInfoUI".equals(eventClass)) {
                // 添加用户信息页面

                List<String> addBookIdList = new ArrayList<>();
                addBookIdList.add("com.tencent.mm:id/cp");
                addBookIdList.add("com.tencent.mm:id/cs");

                for (int i = 0; i < addBookIdList.size(); i++) {

                    String addBookId = addBookIdList.get(i);
                    if (findNodeByViewIdAndText(addBookId, "发消息")) {
                        // 已经是好友了
                        goBack();
                        goBack();
                        userStatus = Config.USER_ADDED_STATUS;
                        addCustomerStep = 10;

                    } else if (findAndClickNodeByViewIdAndText(addBookId, "添加到通讯录")) {

                        addCustomerStep = 6;
                    } else {
                        Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
                    }
                }
            }

        } else if (addCustomerStep == 4) {

            // 出错提示窗口
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.widget.a.c".equals(eventClass)) {

                boolean hasError = false;
                List<String> errorViewIdList = new ArrayList<>();
                errorViewIdList.add("com.tencent.mm:id/d3f");
                errorViewIdList.add("com.tencent.mm:id/om");

                for (int i = 0; i < errorViewIdList.size(); i++) {
                    String errorViewId = errorViewIdList.get(i);
                    if (findNodeByViewId(errorViewId, 0, "出错提示框") != null) {
                        hasError = true;
                        break;
                    }
                }

                if (hasError) {

                    Log.e(TAG, "出错提示框");

                    // 操作频繁或者其他出错
                    if (event.getText() != null && event.getText().size() > 0) {

                        List<CharSequence> textList = event.getText();
                        for (int i = 0; i < textList.size(); i++) {

                            String errorMsg = textList.get(i).toString();

                            Log.e(TAG, "errorMsg:" + errorMsg);

                            if ("操作过于频繁，请稍后再试".equals(errorMsg)) {

                                Log.e(TAG, "触发微信报错，<操作过于频繁，请稍后再试>");

                                // 操作频繁，则等待一段较长的时间
                                frenquetlyWarning = true;
                                TasksWindow.changeMsg("<操作过于频繁，请稍后再试>");

                                break;
                            }
                        }
                    }
                } else {
                    Log.i(TAG, "出错信息未知 addCustomerStep:" + addCustomerStep);
                }


                List<String> okViewIdList = new ArrayList<>();
                okViewIdList.add("com.tencent.mm:id/ayb");
                okViewIdList.add("com.tencent.mm:id/az_");

                boolean foundOk = false;
                for (int i = 0; i < okViewIdList.size(); i++) {
                    String okViewId = okViewIdList.get(i);
                    if (findAndClickNodeByViewIdAndText(okViewId, "确定")) {

                        // "用户不存在" 或者 "操作过于频繁，请稍后再试"

                        userStatus = Config.USER_EMPTY_STATUS;
                        addCustomerStep = 10;

                        foundOk = true;
                    }
                }

                if (!foundOk) {
                    Log.e(TAG, "未找到确定按钮，回退");

                    userStatus = Config.USER_EMPTY_STATUS;
                    addCustomerStep = 10;
                    goBack();
                }

            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.ContactInfoUI".equals(eventClass)) {
                // 添加用户信息页面

                List<String> addBookIdList = new ArrayList<>();
                addBookIdList.add("com.tencent.mm:id/cp");
                addBookIdList.add("com.tencent.mm:id/cs");

                for (int i = 0; i < addBookIdList.size(); i++) {

                    String addBookId = addBookIdList.get(i);
                    if (findNodeByViewIdAndText(addBookId, "发消息")) {
                        // 已经是好友了
                        goBack();
                        goBack();
                        userStatus = Config.USER_ADDED_STATUS;
                        addCustomerStep = 10;

                    } else if (findAndClickNodeByViewIdAndText(addBookId, "添加到通讯录")) {

                        addCustomerStep = 6;
                    } else {
                        Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
                    }
                }


            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }

        } else if (addCustomerStep == 6)

        {
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.base.p".equals(eventClass)) {
                addCustomerStep = 7;

            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.ContactInfoUI".equals(eventClass)) {
                // 点击添加后发现，已经是好友了
                goBack();

                userStatus = Config.USER_ADDED_STATUS;
                addCustomerStep = 11;
                Log.i(TAG, "add success, addCustomerStep:" + addCustomerStep);

            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }

        } else if (addCustomerStep == 7)

        {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.SayHiWithSnsPermissionUI".equals(eventClass)) {


                List<String> helloIdList = new ArrayList<>();
                helloIdList.add("com.tencent.mm:id/dx6");
                helloIdList.add("com.tencent.mm:id/e0o");

                for (int i = 0; i < helloIdList.size(); i++) {
                    String helloId = helloIdList.get(i);

                    //当前所在页面,验证申请
                    if (findNodeByViewId(helloId, 0, "打招呼内容编辑框") != null) {

                        AccessibilityNodeInfo nodeInfo = findNodeByViewId(helloId, 0, "打招呼内容编辑框");
                        if (nodeInfo != null) {

                            String sayHello = "我是-16655885107";

                            SettingDao settingDao = new SettingDao(getApplicationContext());
                            Setting setting = settingDao.findByProperty("sayhello");
                            if (setting != null) {
                                sayHello = setting.getValue();
                            }

                            if (inputTextByNodeInfo(nodeInfo, sayHello, false)) {

                                // 为朋友设置备注
                                AccessibilityNodeInfo noteNodeInfo = findNodeByViewId("com.tencent.mm:id/e0s", 0, "为朋友设置备注");
                                if (noteNodeInfo != null) {

                                    noteNodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                                    noteNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
                                    String day = format.format(new Date());
                                    Log.i(TAG, "为朋友设置备注");
                                    inputTextByNodeInfo(noteNodeInfo, day + "." + user.getUsername(), true);
                                } else {
                                    Log.e(TAG, "<为朋友设置备注> is null");
                                }

                                List<String> sendIdList = new ArrayList<>();
                                sendIdList.add("com.tencent.mm:id/jq");
                                sendIdList.add("com.tencent.mm:id/jx");

                                for (int j = 0; j < sendIdList.size(); j++) {
                                    String sendId = sendIdList.get(j);
                                    if (findAndClickNodeByViewId(sendId, 0, "发送")) {

                                        Log.i(TAG, "添加用户好友申请成功发送");
                                        userStatus = Config.USER_ADDED_STATUS;
                                        addCustomerStep = 8;
                                        break;
                                    }
                                }
                            }
                        }

                    }
                }
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }


        } else if (addCustomerStep == 8)

        {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.base.p".equals(eventClass)) {
                addCustomerStep = 9;
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }


        } else if (addCustomerStep == 9)

        {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.ContactInfoUI".equals(eventClass)) {

                goBack();

                addCustomerStep = 10;
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }
        } else if (addCustomerStep == 10)

        {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.fts.ui.FTSMainUI".equals(eventClass)) {

                // 注意这里需要返回2次
                goBack();
                goBack();

                addCustomerStep = 11;
            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.profile.ui.ContactInfoUI".equals(eventClass)) {

                goBack();
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }
        } else if (addCustomerStep == 11)

        {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.ui.LauncherUI".equals(eventClass)) {

                goBack();

                Log.d(TAG, "更新user信息，nickname：" + user.getNickname() + ", wxid:" + user.getWxid() + ", addCustomerStep:" + addCustomerStep + ", userStatus:" + userStatus);

                // 更新本次处理完，开始下一个用户
                updateAddSuccess(userStatus);

                addCustomerStep = -1;
            } else {
                Log.i(TAG, "do nothing, addCustomerStep:" + addCustomerStep);
            }
        }

    }

    private void updateAddSuccess(String status) {

        UserDao userDao = new UserDao(getApplicationContext());
        // 更新数据为成功
        user.setStatus(status);
        userDao.update(user);

        Log.d(TAG, "更新数据为成功，status = " + status + ", phone:" + user.getPhone() + ", nickname：" + user.getNickname() + ", wxid:" + user.getWxid());
        user = null;

    }

    // 获取用户昵称和微信号
    private void getUserNickNameAndWxId() {

        AccessibilityNodeInfo nickNameNode = findNodeByViewId("com.tencent.mm:id/b2x", 0, "昵称");
        if (nickNameNode != null) {
            if (nickNameNode.getText() != null) {
                user.setNickname(nickNameNode.getText().toString());
            } else if (nickNameNode.getContentDescription() != null) {
                user.setNickname(nickNameNode.getContentDescription().toString());
            } else {
                Log.e(TAG, "获取nickName失败");
            }
        }

        AccessibilityNodeInfo wxNode = findNodeByViewId("com.tencent.mm:id/b35", 0, "wxid");
        if (wxNode != null) {
            if (wxNode.getText() != null) {
                user.setWxid(wxNode.getText().toString());
            } else if (wxNode.getContentDescription() != null) {
                user.setWxid(wxNode.getContentDescription().toString());
            } else {
                Log.e(TAG, "获取wxId失败");
            }
        }


    }

    /**
     * 自动抢红包 =================================================================================分割线=========================================================================================================================
     */

    private void processLuckMoneyEvent(AccessibilityEvent event) {

        // 1.当前在聊天界面，查找并点击领取红包
        if (luckyMoneyStep == -1 && event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {

            // 有人发信息 记录信息内容 会直接点开信息
            if (handleNotification(event, "[微信红包]")) {
                luckyMoneyStep = 1;
            }

        } else if (luckyMoneyStep == 1) {

            if (findAndClickUnOpenEnvelope("微信红包")) {
                luckyMoneyStep = 2;
            } else {

                // 没有更多红包则微信后台运行，等待红包通知
                Log.i(TAG, "没有更多红包了");
                goBack();
                goBack();

                luckyMoneyStep = -1;
            }

        } else if (luckyMoneyStep == 2) {// 3.抢到红包后的详情页面

            if (findAndClickNodeByViewId("com.tencent.mm:id/cv0", 0, "开")) {

                Log.i(TAG, "抢到红包了");
                luckyMoneyStep = 3;
            }

        } else if (luckyMoneyStep == 3) {

            goBack();

            // 继续打开红包
            luckyMoneyStep = 1;
        }

    }

    /**
     * 查找并点击红包
     */
    private boolean findAndClickUnOpenEnvelope(String keyWord) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();

        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ao4");
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, keyWord + " is null");
            return false;
        }

        for (int i = 0; i < bu.size(); i++) {

            AccessibilityNodeInfo nodeInfo = bu.get(i);

            // 已经领取了
            List<AccessibilityNodeInfo> hasDone = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ape");
            if (hasDone != null && hasDone.size() > 0) {
                Log.d(TAG, "<" + keyWord + "> 已经领过了");
                continue;
            }

            int loop = 10;
            while (nodeInfo != null && !nodeInfo.isClickable() && loop > 0) {
                loop--;
                nodeInfo = nodeInfo.getParent();
            }

            if (nodeInfo != null) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                Log.d(TAG, "点击 <" + keyWord + ">");
                return true;
            }
            Log.d(TAG, "<" + keyWord + "> 不能点击");


        }

        return false;

    }


    /**
     * 自动添加附近的人 =================================================================================分割线=========================================================================================================================
     */


    private void processNearbyEvent(AccessibilityEvent event) {


        // 微信主页面，依次点击：发现->附近的人
        if (addNearbyStep == -1) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/d3t", 2, "发现")) {
                addNearbyStep = 0;
            }

        } else if (addNearbyStep == 0) {
            if (findAndClickNodeByViewId("android:id/title", 8, "附近的人")) {
                addNearbyStep = 1;
            }

        } else if (addNearbyStep == 1) {

            AccessibilityNodeInfo rootNode = getRootInActiveWindow();

            if (rootNode == null) {
                Log.e(TAG, "rootNode is null");
                return;
            }

            List<AccessibilityNodeInfo> list = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/bex");
            if (list == null || list.size() <= 0) {
                Log.e(TAG, "list is null");
                return;
            }

            for (int i = 0; i < list.size(); i++) {

                AccessibilityNodeInfo parent = list.get(i);

                String wxNick = parent.getText().toString();

                // 已经添加过了
                if (nearbySet.contains(wxNick)) {
                    continue;
                }

                while (parent != null && !parent.isClickable()) {
                    parent = parent.getParent();
                }

                // 没有找到可点击node
                if (parent == null) {
                    Log.e(TAG, "node 不可点击");
                    continue;
                }

                Log.i(TAG, "点击 <" + wxNick + ">");
                nearbySet.add(wxNick);
                parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                addNearbyStep = 2;

                return;
            }

            goBack();
            goBack();
            addNearbyStep = -1;

        } else if (addNearbyStep == 2) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/cp", 0, "打招呼")) {
                addNearbyStep = 3;
            }

        } else if (addNearbyStep == 3) {

            AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/dx6", 0, "打招呼内容编辑框");
            if (nodeInfo != null) {

                String sayHello = "我是李延凯";

                SettingDao settingDao = new SettingDao(getApplicationContext());
                Setting setting = settingDao.findByProperty("sayhello");
                if (setting != null) {
                    sayHello = setting.getValue();
                }

                inputTextByNodeInfo(nodeInfo, sayHello, true);

                // 5.点击好友申请发送
                if (findAndClickNodeByViewId("com.tencent.mm:id/jq", 0, "发送")) {
                    addNearbyStep = 4;
                }
            }

        } else if (addNearbyStep == 4) {
            goBack();
            addNearbyStep = 1;
        }
    }

    /**
     * 自动发朋友圈 =================================================================================分割线=========================================================================================================================
     */

    private void processPostSns(AccessibilityEvent event) {

        int eventType = event.getEventType();
        String className = event.getClassName() != null ? event.getClassName().toString() : "";

        //第一次启动app
        if (postSnsStep == -1) {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.ui.LauncherUI".equals(className)) {

                List<String> navViewIdList = new ArrayList<>();
                navViewIdList.add("com.tencent.mm:id/d3t");
                navViewIdList.add("com.tencent.mm:id/d7b");

                for (int i = 0; i < navViewIdList.size(); i++) {
                    String navViewId = navViewIdList.get(i);
                    if (findAndClickNodeByViewId(navViewId, 2, "发现")) {
                        postSnsStep = 0;
                        break;
                    }
                }
            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && "com.tencent.mm.plugin.account.ui.LoginPasswordUI".equals(className)) {

                goBack();
                // 停止发送
                Config.taskMask = Config.MASK_DEFAULT;

                Log.i(TAG, "微信号未登录");

            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }

        } else if (postSnsStep == 0) {

            if (eventType == TYPE_WINDOWS_CHANGED || eventType == TYPE_VIEW_SCROLLED || "com.tencent.mm.ui.mogic.WxViewPager".equals(className)) {

                List<String> friendList = new ArrayList<>();
                friendList.add("com.tencent.mm:id/d7v");

                AccessibilityNodeInfo root = getRootInActiveWindow();
                if (root != null) {

                    for (int i = 0; i < friendList.size(); i++) {

                        List<AccessibilityNodeInfo> d7vNodeList = root.findAccessibilityNodeInfosByViewId(friendList.get(i));

                        if (d7vNodeList != null && d7vNodeList.size() > 0) {

                            for (int j = 0; j < d7vNodeList.size(); j++) {
                                List<AccessibilityNodeInfo> friendNodeList = d7vNodeList.get(j).findAccessibilityNodeInfosByText("朋友圈");

                                if (friendNodeList != null && friendNodeList.size() > 0) {

                                    for (int k = 0; k < friendList.size(); k++) {
                                        AccessibilityNodeInfo friendNode = friendNodeList.get(k);

                                        int loop = 15;
                                        while (friendNode != null && !friendNode.isClickable() && loop > 0) {
                                            friendNode = friendNode.getParent();
                                            loop--;
                                        }

                                        if (friendNode != null && friendNode.isClickable()) {
                                            friendNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                            postSnsStep = 1;
                                        } else {
                                            Log.i(TAG, "朋友圈不可点击");
                                        }
                                    }
                                } else {
                                    Log.e(TAG, "no 朋友圈");
                                }
                            }
                        }
                    }
                }
            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }

        } else if (postSnsStep == 1) {
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.plugin.sns.ui.SnsTimeLineUI".equals(className)) {

                List<String> photoViewIdList = new ArrayList<>();
                photoViewIdList.add("com.tencent.mm:id/jr");
                photoViewIdList.add("com.tencent.mm:id/jy");

                for (int i = 0; i < photoViewIdList.size(); i++) {
                    String photoId = photoViewIdList.get(i);
                    if (findAndClickNodeByViewId(photoId, 0, "拍照分享")) {
                        postSnsStep = 2;
                        break;
                    }
                }

            } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.ui.widget.a.c".equals(className)) {
                if (findAndClickNodeByText("知道了")) {
                    Log.i(TAG, "click 知道了，postSnsStep:" + postSnsStep);
                }
            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }

        } else if (postSnsStep == 2) {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.ui.base.k".equals(className)) {

                List<String> albumViewIdList = new ArrayList<>();
                albumViewIdList.add("com.tencent.mm:id/ct");
                albumViewIdList.add("com.tencent.mm:id/cw");

                for (int i = 0; i < albumViewIdList.size(); i++) {
                    String albumId = albumViewIdList.get(i);
                    if (findAndClickNodeByViewId(albumId, 1, "从相册选择")) {
                        postSnsStep = 3;
                        break;
                    }
                }
            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }
        } else if (postSnsStep == 3) {
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.plugin.gallery.ui.AlbumPreviewUI".equals(className)) {

                List<String> imgSelectViewList = new ArrayList<>();
                imgSelectViewList.add("com.tencent.mm:id/bmv");
                imgSelectViewList.add("com.tencent.mm:id/bou");
                for (int i = 0; i < imgSelectViewList.size(); i++) {
                    String imgViewId = imgSelectViewList.get(i);
                    if (findAndClickNodeByViewId(imgViewId, 0, "选择框")) {
                        postSnsStep = 4;
                        break;
                    }
                }
            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }
        } else if (postSnsStep == 4) {

            if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED || "android.view.View".equals(className)) {

                List<String> imgFinishViewList = new ArrayList<>();
                imgFinishViewList.add("com.tencent.mm:id/jq");
                imgFinishViewList.add("com.tencent.mm:id/jx");

                for (int i = 0; i < imgFinishViewList.size(); i++) {
                    String imgFinishViewId = imgFinishViewList.get(i);
                    if (findAndClickNodeByViewId(imgFinishViewId, 0, "完成")) {
                        postSnsStep = 5;
                        break;
                    }
                }

            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }
        } else if (postSnsStep == 5) {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.plugin.sns.ui.SnsUploadUI".equals(className)) {

                List<String> contentViewList = new ArrayList<>();
                contentViewList.add("com.tencent.mm:id/cox");
                contentViewList.add("com.tencent.mm:id/cqx");

                for (int i = 0; i < contentViewList.size(); i++) {
                    String contentViewId = contentViewList.get(i);
                    AccessibilityNodeInfo contentNodeInfo = findNodeByViewId(contentViewId, 0, "朋友圈内容编辑框");

                    if (contentNodeInfo != null) {

                        // 点击
                        contentNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                        String postsns = "测试朋友圈，一会儿删除";

                        SettingDao settingDao = new SettingDao(getApplicationContext());
                        Setting setting = settingDao.findByProperty(Config.SNS_CONTENT_KEY);
                        if (setting != null) {
                            postsns = setting.getValue();

                            settingDao = new SettingDao(getApplicationContext());
                            setting.setStatus("2");
                            settingDao.update(setting);
                            Log.i(TAG, "update sns status");
                        }

                        inputTextByNodeInfo(contentNodeInfo, postsns, true);

                        List<String> postViewIdList = new ArrayList<>();
                        postViewIdList.add("com.tencent.mm:id/jq");
                        postViewIdList.add("com.tencent.mm:id/jx");
                        for (int j = 0; j < postViewIdList.size(); j++) {
                            String postViewId = postViewIdList.get(j);
                            if (findAndClickNodeByViewId(postViewId, 0, "发表")) {
                                postSnsStep = 6;
                                break;
                            }
                        }

                        break;
                    }
                }

            }
        } else if (postSnsStep == 6) {
            if (event.getClassName() != null && "com.tencent.mm.plugin.sns.ui.SnsTimeLineUI".equals(event.getClassName().toString())) {

                goBack();
                postSnsStep = 7;
            }

        } else if (postSnsStep == 7) {

            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.ui.LauncherUI".equals(className)) {

                goBack();
                postSnsStep = 8;
            }
        } else if (postSnsStep == 8) {
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || "com.tencent.mm.ui.LauncherUI".equals(className)) {

                List<String> navViewIdList = new ArrayList<>();
                navViewIdList.add("com.tencent.mm:id/d3t");
                navViewIdList.add("com.tencent.mm:id/d7b");

                for (int i = 0; i < navViewIdList.size(); i++) {
                    String navViewId = navViewIdList.get(i);
                    if (findAndClickNodeByViewId(navViewId, 0, "微信")) {
                        postSnsStep = 9;

                        updatePostSnsSuccess(Config.SNS_DONE_STATUS);

                        break;
                    }
                }
            } else {
                Log.i(TAG, "do nothing, postSnsStep:" + postSnsStep);
            }
        } else if (postSnsStep == 9) {

            performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
            // 停止发送
            Config.taskMask = Config.MASK_DEFAULT;

            Log.d(TAG, "user is null, 按下Home键，taskMask：" + Config.taskMask + ", addCustomerStep:" + addCustomerStep);
        }

    }


    private void updatePostSnsSuccess(String status) {

        SettingDao settingDao = new SettingDao(getApplicationContext());

        if (setting != null) {
            // 更新数据为成功
            setting.setStatus(status);
            settingDao.update(setting);

            Log.d(TAG, "更新数据为成功, getProperty:" + setting.getProperty() + ", getValue：" + setting.getValue());
            setting = null;
        }

    }


    /**
     * 自动点赞 =================================================================================分割线=========================================================================================================================
     */

    private void processAutoPrize(AccessibilityEvent event) {


        if (snsAutoPrizeStep == -1) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/d3t", 2, "发现")) {
//                doSleep(3000);
                snsAutoPrizeStep = 0;
            }

        } else if (snsAutoPrizeStep == 0) {
            if (findAndClickNodeByText("朋友圈")) {
//                doSleep(3000);
                snsAutoPrizeStep = 1;
            }

        } else if (snsAutoPrizeStep == 1) {
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();

            if (rootNode == null) {
                Log.e(TAG, "rootNode is null");
                return;
            }

            List<AccessibilityNodeInfo> list = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/efo");
            if (list == null || list.size() <= 0) {
                Log.e(TAG, "list is null");
                return;
            }

            for (int i = 0; i < list.size(); i++) {
                AccessibilityNodeInfo nodeInfo = list.get(i);

                if (nodeInfo == null || nodeInfo.getChildCount() < 2) {

                    Log.i(TAG, "朋友圈内容 为空");
                    continue;
                }

                // 已经点赞过了
                List<AccessibilityNodeInfo> hasPrizedList = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/efb");
                if (hasPrizedList != null && hasPrizedList.size() > 0) {
                    continue;
                }

                // 三个点
                List<AccessibilityNodeInfo> threeDotList = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/eb6");
                if (threeDotList == null) {

                    Log.e(TAG, "... 为空");
                    continue;
                }

                AccessibilityNodeInfo threeDot = threeDotList.get(0);
                if (threeDot == null || !threeDot.isClickable()) {

                    Log.e(TAG, "... 不能点击");
                    continue;
                }


                Log.i(TAG, "点击 <...>");
                threeDot.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                doSleep(2000);

                snsAutoPrizeStep = 3;
                return;
            }

            goBack();
            goBack();
            goBack();
            snsAutoPrizeStep = -1;

        } else if (snsAutoPrizeStep == 3) {
            if (findAndClickNodeByViewId("com.tencent.mm:id/eac", 0, "赞")) {
                doSleep(2000);
                snsAutoPrizeStep = 4;
            }

        } else if (snsAutoPrizeStep == 4) {
            snsAutoPrizeStep = 1;
        }

    }


    /**
     * 自动从群里面添加好友 =================================================================================分割线=========================================================================================================================
     */

    private void processAcceptFriendAdd2Group(AccessibilityEvent event) {


        if (acceptAdd2GroupStep == -1) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/d3t", 1, "通讯录")) {
                acceptAdd2GroupStep = 0;
            }

        } else if (acceptAdd2GroupStep == 0) {
            if (findAndClickNodeByViewId("com.tencent.mm:id/brc", 0, "新的朋友")) {
                acceptAdd2GroupStep = 1;
            }
        } else if (acceptAdd2GroupStep == 1) {

            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode == null) {
                Log.e(TAG, "rootNode is null");
                return;
            }

            List<AccessibilityNodeInfo> acceptList = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/brs");

            if (acceptList == null || acceptList.size() <= 0) {
                Log.e(TAG, "acceptList is null");

                if (groupSet == null || groupSet.size() <= 0) {
                    return;
                }
            } else {

                for (int i = 0; i < acceptList.size(); i++) {
                    AccessibilityNodeInfo nodeInfo = acceptList.get(i);

                    if (nodeInfo == null || !nodeInfo.isClickable()) {
                        Log.i(TAG, "nodeInfo 不可点击");
                        continue;
                    }

                    String wxNikeName = nodeInfo.getParent().getParent().getChild(0).getChild(0).getText().toString();

                    if (groupSet.contains(wxNikeName)) {
                        continue;
                    }

                    groupSet.add(wxNikeName);
                    Log.i(TAG, "点击 <接受>:" + wxNikeName);
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    acceptAdd2GroupStep = 2;
                    return;
                }
            }

            // 测试
            groupSet.add("晓晓");

            // 有新申请
            if (groupSet.size() > 0) {
                goBack();
                acceptAdd2GroupStep = 3;
            }
        } else if (acceptAdd2GroupStep == 2) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/jq", 0, "完成")) {
                goBack();
                acceptAdd2GroupStep = 1;
            }
        } else if (acceptAdd2GroupStep == 3) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/mn", 0, "群聊")) {
                acceptAdd2GroupStep = 4;
            }
        } else if (acceptAdd2GroupStep == 4) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/by", 0, "搜索")) {
                acceptAdd2GroupStep = 5;
            }
        } else if (acceptAdd2GroupStep == 5) {

            AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/ka", 0, "群组搜索名字输入框");
            if (nodeInfo == null) {
                Log.e(TAG, "nodeinfo is null");
                return;
            }

            if (inputTextByNodeInfo(nodeInfo, "趣米花", true)) {
                acceptAdd2GroupStep = 6;
            }

        } else if (acceptAdd2GroupStep == 6) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/my", 0, "群聊")) {
                acceptAdd2GroupStep = 7;
            }
        } else if (acceptAdd2GroupStep == 7) {

            AccessibilityNodeInfo rootNode = getRootInActiveWindow();

            if (rootNode == null) {
                Log.e(TAG, "rootNode is null");
                return;
            }

            List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/jr");
            if (bu == null || bu.isEmpty()) {
                Log.e(TAG, "... is null");
                return;
            }

            for (int i = 0; i < bu.size(); i++) {
                AccessibilityNodeInfo nodeInfo = bu.get(i);

                if ("聊天信息".equals(nodeInfo.getContentDescription().toString())) {

                    while (nodeInfo != null && !nodeInfo.isClickable()) {
                        nodeInfo = nodeInfo.getParent();
                    }

                    if (nodeInfo != null) {

                        Log.i(TAG, "点击 <...>");
                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                        acceptAdd2GroupStep = 8;
                        return;
                    }

                    Log.i(TAG, "<...> 不能点击");

                }
            }

        } else if (acceptAdd2GroupStep == 8) {

            // 添加完了
            if (groupSet == null || groupSet.size() <= 0) {

                goBack();
                goBack();
                goBack();
                goBack();

                acceptAdd2GroupStep = -1;
                return;
            }

            AccessibilityNodeInfo rootNode = getRootInActiveWindow();

            if (rootNode == null) {
                Log.e(TAG, "rootNode is null");
                return;
            }

            List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dwu");
            if (bu == null || bu.isEmpty()) {
                Log.e(TAG, "+号 is null");
                return;
            }

            for (int i = 0; i < bu.size(); i++) {
                AccessibilityNodeInfo nodeInfo = bu.get(i);

                if ("添加成员".equals(nodeInfo.getContentDescription().toString())) {

                    while (nodeInfo != null && !nodeInfo.isClickable()) {
                        nodeInfo = nodeInfo.getParent();
                    }

                    if (nodeInfo != null) {

                        Log.i(TAG, "点击 <+号>");
                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                        acceptAdd2GroupStep = 9;
                        return;
                    }

                    Log.i(TAG, "<+号> 不能点击");

                }
            }
        } else if (acceptAdd2GroupStep == 9) {

            AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/b79", 0, "搜索用户名输入框");

            if (nodeInfo == null) {
                Log.e(TAG, "nodeinfo is null");
                return;
            }

            if (groupSet != null && groupSet.size() > 0) {

                String wxNickName = "测试";

                Iterator<String> iterator = groupSet.iterator();
                if (iterator.hasNext()) {
                    wxNickName = iterator.next();
                }

                if (inputTextByNodeInfo(nodeInfo, wxNickName, true)) {

                    Log.i(TAG, "添加用户:" + wxNickName);
                    groupSet.remove(wxNickName);
                    acceptAdd2GroupStep = 10;

                    doSleep(1000);
                }
            }


        } else if (acceptAdd2GroupStep == 10) {

            AccessibilityNodeInfo nodeInfo = findNodeByViewId("com.tencent.mm:id/i8", 0, "遮罩层");

            if (nodeInfo == null) {


                AccessibilityNodeInfo checkBox = findNodeByViewId("com.tencent.mm:id/zk", 0, "选中框");

                if (checkBox == null) {
                    Log.e(TAG, "checkBox is null");
                    return;
                } else if (!checkBox.isEnabled()) {
                    goBack();
                    acceptAdd2GroupStep = 8;
                } else {

                    while (checkBox != null && !checkBox.isClickable()) {
                        checkBox = checkBox.getParent();
                    }

                    if (checkBox != null) {
                        Log.i(TAG, "选中 <选中框>");
                        checkBox.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                    acceptAdd2GroupStep = 11;
                }
            } else {

                goBack();
                acceptAdd2GroupStep = 8;
            }

        } else if (acceptAdd2GroupStep == 11) {

            if (findAndClickNodeByViewId("com.tencent.mm:id/jq", 0, "确定")) {
                acceptAdd2GroupStep = 8;
            }

        }


    }


    /**
     * 工具方法 =================================================================================分割线=========================================================================================================================
     */

    /**
     * 查找节点
     */
    private AccessibilityNodeInfo findNodeByViewId(String viewId, int index, String keyWord) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return null;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, "viewId:<" + viewId + ">, keyWord:<" + keyWord + "> is null");

//            rootNode.recycle();
            return null;
        }

        Log.d(TAG, "获取 <" + keyWord + ">");

//        rootNode.recycle();


        AccessibilityNodeInfo target = null;
        if (index == -1) {
            for (int i = 0; i < bu.size(); i++) {
                AccessibilityNodeInfo nodeInfo = bu.get(i);
                if (nodeInfo.getText() != null && keyWord.equals(nodeInfo.getText())) {
                    target = nodeInfo;
                    break;
                }
            }
        } else {
            target = bu.get(index);
        }

        return target;
    }

    /**
     * 查找并点击要素
     */
    private boolean findAndClickNodeByViewIdAndText(String viewId, String text) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();

        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, text + " is null");
            return false;
        }

        for (int i = 0; i < bu.size(); i++) {

            AccessibilityNodeInfo nodeInfo = bu.get(i);

            int loop = 10;

            if (nodeInfo != null && nodeInfo.getText() != null && text.equals(nodeInfo.getText().toString())) {

                while (nodeInfo != null && !nodeInfo.isClickable() && loop > 0) {
                    loop--;
                    nodeInfo = nodeInfo.getParent();
                }

                if (nodeInfo != null) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    Log.d(TAG, "点击 <" + text + ">");

                    return true;
                }
            } else {
                if (nodeInfo != null && nodeInfo.getText() != null) {
                    Log.d(TAG, "text <" + text + "> != <" + nodeInfo.getText().toString() + ">");

                } else {
                    Log.d(TAG, "text <" + text + "> != <" + null + ">");
                }
            }
        }

        rootNode.recycle();

        Log.d(TAG, "未找到可点击的 <" + text + ">");

        return false;
    }

    /**
     * 查找并点击要素
     */
    private boolean findNodeByViewIdAndText(String viewId, String text) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();

        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, text + " is null");
            return false;
        }

        for (int i = 0; i < bu.size(); i++) {

            AccessibilityNodeInfo nodeInfo = bu.get(i);

            int loop = 10;

            if (nodeInfo.getText() != null && text.equals(nodeInfo.getText().toString())) {

                while (nodeInfo != null && !nodeInfo.isClickable() && loop > 0) {
                    loop--;
                    nodeInfo = nodeInfo.getParent();
                }

                if (nodeInfo != null) {

                    Log.d(TAG, "找到 <" + text + ">");

                    return true;
                }
            } else {
                if (nodeInfo.getText() != null) {
                    Log.d(TAG, "text <" + text + "> != <" + nodeInfo.getText().toString() + ">");

                } else {
                    Log.d(TAG, "text <" + text + "> != <" + null + ">");
                }
            }
        }

        rootNode.recycle();

        Log.d(TAG, "未找到可点击的 <" + text + ">");

        return false;
    }

    /**
     * 查找并点击要素
     *
     * @param viewId
     * @param index
     * @param keyWord
     * @return
     */
    private boolean findAndClickNodeByViewId(String viewId, int index, String keyWord) {

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();

        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, keyWord + " is null");

            rootNode.recycle();
            return false;
        }

        AccessibilityNodeInfo nodeInfo = bu.get(index);

        int loop = 10;
        while (nodeInfo != null && !nodeInfo.isClickable() && loop > 0) {
            loop--;
            nodeInfo = nodeInfo.getParent();
        }

        if (nodeInfo != null) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

            Log.d(TAG, "点击 <" + keyWord + ">");

            rootNode.recycle();
            return true;
        }

        Log.d(TAG, "<" + keyWord + "> 不能点击");

        rootNode.recycle();
        return false;
    }


    /**
     * 查找并点击要素，文本遍历循环
     *
     * @param text
     * @return
     */
    private boolean findAndClickNodeByText(String text) {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) {

            Log.e(TAG, "rootNode is null");
            return false;
        }

        List<AccessibilityNodeInfo> bu = rootNode.findAccessibilityNodeInfosByText(text);
        if (bu == null || bu.isEmpty()) {
            Log.e(TAG, text + " is null");
            return false;
        }

        for (int i = 0; i < bu.size(); i++) {
            AccessibilityNodeInfo nodeInfo = bu.get(i);

            int loop = 10;
            while (nodeInfo != null && !nodeInfo.isClickable() && loop > 0) {
                loop--;
                nodeInfo = nodeInfo.getParent();
            }

            if (nodeInfo != null) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                Log.d(TAG, "点击 <" + text + ">");

                return true;
            } else {
                continue;
            }
        }

        Log.d(TAG, "<" + text + "> 不能点击");

        return false;
    }

    /**
     * EditText 输入内容
     *
     * @param nodeInfo
     * @param text
     * @param isFromStart
     */
    private boolean inputTextByNodeInfo(AccessibilityNodeInfo nodeInfo, String text, boolean isFromStart) {

        if (nodeInfo == null) {
            Log.e(TAG, "nodeInfo is null");
            return false;
        }

        // 这个很重要
        while (!nodeInfo.isEditable()) {
            doSleep(1000);
            Log.d(TAG, "等待输入框变得可用");
        }

        Log.d(TAG, "Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);

        Bundle arguments = new Bundle();

        // 这里为设置仅仅是选中一行，也可以设置选中一个单词 或者一整页之类，看具体需要吧
        arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE);
        arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, true);

        // 这里是因为有的EditText的光标默认是在文字最后面，有的则是默认在文字最前面
        // 所以我们加多一个判断，究竟是从前往后全选，还是从后往前全选
        if (isFromStart) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, arguments);
        } else {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, arguments);
        }

        // 2. 保存目标文字到剪切板
        ClipData clip = ClipData.newPlainText("label", text);
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(clip);

        // 3. 最后将剪切板中的文字复制到节点中已经全选的文字
        doSleep(200);
        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);

        Log.i(TAG, "粘贴回复内容：【" + text + "】");
//        }

        return true;
    }

    /**
     * EditText 输入内容
     *
     * @param text
     * @param isFromStart
     */
    private boolean inputTextByViewId(AccessibilityNodeInfo inputNode, String text, boolean isFromStart) {

        if (inputNode == null) {
            Log.e(TAG, "inputNode is null");
            return false;
        }

        // 这个很重要
        while (!inputNode.isEditable()) {
            doSleep(1000);
            Log.d(TAG, "等待输入框变得可用");
        }

        Log.d(TAG, "Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= 21) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
            inputNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);

            Log.i(TAG, "粘贴回复内容：【" + text + "】");

        } else {
            Bundle arguments = new Bundle();

            // 这里为设置仅仅是选中一行，也可以设置选中一个单词 或者一整页之类，看具体需要吧
            arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
            arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, true);

            // 这里是因为有的EditText的光标默认是在文字最后面，有的则是默认在文字最前面
            // 所以我们加多一个判断，究竟是从前往后全选，还是从后往前全选
            if (isFromStart) {
                inputNode.performAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, arguments);
            } else {
                inputNode.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, arguments);
            }

            // 2. 保存目标文字到剪切板
            ClipData clip = ClipData.newPlainText("label", text);
            ClipboardManager clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(clip);

            // 3. 最后将剪切板中的文字复制到节点中已经全选的文字
            inputNode.performAction(AccessibilityNodeInfo.ACTION_PASTE);

            Log.i(TAG, "粘贴回复内容：【" + text + "】");
        }

//        inputNode.recycle();
        return true;
    }


    /***
     * 返回键
     *
     * @return
     */
    private boolean goBack() {

        doSleep(200);

        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);

        doSleep(200);

        return true;


    }

    // 延时
    private void doSleep(long millis) {

        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 自动抓取群信息 =================================================================================分割线=========================================================================================================================
     */

    /**
     * @param event
     */
    public void processCrawlGroupMsg(final AccessibilityEvent event) {


    }

    /**
     * 父类方法 =================================================================================分割线=========================================================================================================================
     */

    @Override
    public void onInterrupt() {

        Log.i(TAG, "服务已中断");
        Toast.makeText(this, "服务已中断", Toast.LENGTH_SHORT).show();
    }


    @Override
    public boolean onUnbind(Intent intent) {


        if (mWakelock != null) {
            mWakelock.release();
        }

        TasksWindow.dismiss();

        // 声音提示
        if (mediaplayer != null) {
            mediaplayer.stop();
            mediaplayer.release();
            mediaplayer = null;
        }

        return super.onUnbind(intent);

    }

    @Override
    public void onDestroy() {

        if (mWakelock != null) {
            mWakelock.release();
        }

        Log.i(TAG, "onDestroy停止了，请重新开启");

        // 服务停止，重新进入系统设置界面
        AccessibilityUtil.jumpToSetting(this);
    }


    /**
     * 唤醒点亮和解锁屏幕(60s)
     */
    public void wakeUpScreenAndWeiXin(Context context) {
        try {

            // 唤醒微信
            ComponentName component = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            Intent intent = new Intent();
            intent.setComponent(component);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            Log.i(TAG, "唤醒微信");


        } catch (Throwable e) {
            Log.e(TAG, "wakeUpScreen: " + e.getMessage());
        }
    }

}
